package com.potenza.training.dictionary.controller;

import com.potenza.training.dictionary.entity.*;
import com.potenza.training.dictionary.server.ProjectEnvironmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hope")
public class ProjectEnvironmentController {

    @Autowired
    private ProjectEnvironmentService projectEnvironmentService;

    static List<EnvironmentOne> environmentOneList = new ArrayList<EnvironmentOne>();

    /**
     * 获取所有的项目环境
     * @return
     */
    @GetMapping("/project/environment")
    public List<ProjectEnvironment> findAll(){
        return projectEnvironmentService.findAll();
    }

    /**
     * 获取经过处理的项目环境
     * @return
     */
    @GetMapping("/project/environments")
    public List<EnvironmentOne> edit(){
        environmentOneList.clear();
        List<ProjectEnvironment> all = findAll();
        for (ProjectEnvironment projectEnvironment : all) {
            environmentOneList.add(new EnvironmentOne(projectEnvironment.getId(),projectEnvironment.getName(),projectEnvironment.getPid(),projectEnvironment.getTypeId(),null));
        }

        List<EnvironmentOne> collect = environmentOneList.stream().filter(environmentOne ->
                environmentOne.getPid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, environmentOneList));
            return menu;
        }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子类菜单
    private static List<EnvironmentOne> getChildrens(EnvironmentOne root,List<EnvironmentOne> all){
        List<EnvironmentOne> children = all.stream().filter(linkageEntities -> Long.parseLong(String.valueOf(linkageEntities.getPid()))==root.getId()).map(linkageEntities -> {
            //1、递归找到子菜单
            linkageEntities.setChildren(getChildrens(linkageEntities,all));
            return linkageEntities;
        }).collect(Collectors.toList());
        return children;
    }

}
